package nbcp.base.model


open class DualPoolMap<K, V>() : DualPoolData<MutableMap<K, V>>(mutableMapOf<K, V>(), mutableMapOf<K, V>()) {

    fun addItem(key: K, value: V) {
        inputPool.put(key, value);
    }


    override val total: Int get() = inputPool.size + outputPool.size

    /**
     * 获取一个并移除
     */
    fun peekOne(): Pair<K, V>? {
        var keys = outputPool.keys;
        if (keys.size == 0) {
            return null;
        }
        var key = keys.first();
        var value = outputPool[key]!!;

        outputPool.remove(key);
        return key to value;
    }


    override fun consumePool(pool: MutableMap<K, V>) {
        if (consumer == null) return;

        pool.keys.forEach { key ->
            val value = pool.get(key);
            if (value != null) {
                consumer!!.invoke(key, value)
            }
            pool.remove(key);
        }
    }


    private var consumer: ((K, V) -> Unit)? = null
    fun consumer(consumer: (K, V) -> Unit): DualPoolMap<K, V> {
        this.consumer = consumer;
        return this;
    }

    /**
     * 清除所有存储空间的指定key
     */
    fun removeAllItem(key: K) {
        masterPool.remove(key);
        alternatePool.remove(key);
    }
}